package services

import (
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"grpc-6/helper"
)

var gDownloader = &helper.Downloader{}

type DownloadServer struct {
}

func (d *DownloadServer) Download(in *DownloadRequest, stream DownloadService_DownloadServer) error {
	err := gDownloader.Download(in.FilePath, func(buffer []byte) error {
		return stream.Send(&DownloadResponse{
			Buffer: buffer,
		})
	})

	if helper.EndOfError == err {
		return status.Error(codes.Code(helper.EOF), helper.CodeToStr(helper.EOF))
	}

	if helper.NormallyCloseError == err {
		return status.Error(codes.Code(helper.NORMALLY_EXIST), helper.CodeToStr(helper.NORMALLY_EXIST))
	}

	return err
}
